package vip.xls8z.learning.nio.channel;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

@Slf4j
@DisplayName("FileChannel 测试")
public class FileChannelTests {

    static RandomAccessFile randomAccessFile;

    @BeforeAll
    public static void beforeAll() throws FileNotFoundException {
        randomAccessFile = new RandomAccessFile(new File("/Users/jason/Documents/IdeaProject/nio-learning/src/main/resources/test.txt"), "rw");
    }

    @Test
    public void readFile() throws IOException {
        FileChannel channel = randomAccessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(128);
        int read = channel.read(buffer);
        if (read != -1) {
            buffer.flip();
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer);
            log.info("{}", charBuffer);
        }
        channel.close();
    }

    @Test
    public void writeFile() throws IOException {
        FileChannel channel = randomAccessFile.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(128);
        byteBuffer.put("Write String".getBytes(StandardCharsets.UTF_8));
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            channel.write(byteBuffer);
        }
        channel.force(true);
        channel.close();
    }

}
